package com.yc;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.MemoryId;
import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.UserMessage;

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.time.Duration;
import java.util.Properties;

/**
 * AI Service 接入心知天气API（基于指定接口）
 */
public class AiServiceWithWeatherAPI {

    // 心知天气API配置
    private static final String API_KEY = "S9ABcP7or9ROC1lzu"; // 替换为你的API密钥
    private static final String API_URL = "https://api.seniverse.com/v3/weather/now.json";

    // QQ邮箱配置
    private static final String SMTP_HOST = "smtp.qq.com";
    private static final int SMTP_PORT = 465;
    private static final String EMAIL_FROM = "2381501220@qq.com"; // 替换为你的QQ邮箱
    private static final String EMAIL_PASSWORD = "aohstiyriieceabi"; // 替换为你的授权码

    // 工具类
    static class MyTools {
        // 天气数据模型（与API响应匹配）
        public static class WeatherResponse {
            @SerializedName("results")
            private java.util.List<WeatherResult> results;

            public java.util.List<WeatherResult> getResults() {
                return results;
            }
        }

        public static class WeatherResult {
            @SerializedName("location") private Location location;
            @SerializedName("now") private WeatherNow now;
            @SerializedName("last_update") private String lastUpdate;

            public Location getLocation() {
                return location;
            }

            public WeatherNow getNow() {
                return now;
            }

            public String getLastUpdate() {
                return lastUpdate;
            }
        }

        public static class Location {
            @SerializedName("name") private String name;

            public String getName() {
                return name;
            }
        }

        public static class WeatherNow {
            @SerializedName("text") private String text;
            @SerializedName("temperature") private String temperature;

            public String getText() {
                return text;
            }

            public String getTemperature() {
                return temperature;
            }
        }

        // 获取天气数据的核心方法（与你提供的接口一致）
        public WeatherResponse getWeather(String location, String unit) throws IOException {
            OkHttpClient client = new OkHttpClient();
            HttpUrl httpUrl = HttpUrl.parse(API_URL).newBuilder()
                    .addQueryParameter("key", API_KEY)
                    .addQueryParameter("location", location)
                    .addQueryParameter("language", "zh-Hans")
                    .addQueryParameter("unit", unit)
                    .build();
            Request request = new Request.Builder().url(httpUrl).build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful())
                    throw new IOException("API请求失败: " + response.code() + ", " + response.message());
                String jsonData = response.body().string();
                return new Gson().fromJson(jsonData, WeatherResponse.class);
            }
        }

        // 在MyTools类中添加邮件发送工具
        @Tool("将文本内容发送到QQ邮箱")
        public String sendTextToQQMail(
                @P("邮件标题") String subject,
                @P("邮件内容") String content,
                @P("收件人邮箱") String recipient) {
            try {
                // 构建HTML邮件内容（简单格式化）
                String htmlContent = "<html>" +
                        "<body style=\"font-family: 'Microsoft YaHei', Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;\">" +
                        "<h2 style=\"color: #333;\">" + subject + "</h2>" +
                        "<div style=\"background-color: #f9f9f9; padding: 15px; border-radius: 5px;\">" +
                        "<p>" + content.replace("\n", "<br>") + "</p>" +
                        "</div>" +
                        "<p style=\"color: #777; font-size: 14px; margin-top: 20px;\">发送时间: " +
                        java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + "</p>" +
                        "</body>" +
                        "</html>";

                // 调用邮件发送方法
                sendMail(recipient, subject, htmlContent);
                return "已将内容发送至" + recipient;

            } catch (Exception e) {
                return "发送邮件失败: " + e.getMessage();
            }
        }

        // 邮件发送方法（保持原有实现不变）
        private void sendMail(String recipient, String subject, String content) throws MessagingException {
            Properties props = new Properties();
            props.put("mail.smtp.host", SMTP_HOST);
            props.put("mail.smtp.port", SMTP_PORT);
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.ssl.enable", "true");

            // 创建邮件会话，提供认证信息
            Session session = Session.getInstance(props, new jakarta.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    System.out.println("认证信息 - 邮箱: " + EMAIL_FROM + ", 密码长度: " + EMAIL_PASSWORD.length());
                    return new PasswordAuthentication(EMAIL_FROM, EMAIL_PASSWORD);
                }
            });


            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(EMAIL_FROM));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
            message.setSubject(subject);
            message.setContent(content, "text/html; charset=utf-8");

            Transport.send(message);
        }

        @Tool("返回给定城市的天气")
        public String getWeatherInfo(
                @P("城市名称") String city,
                @P("温度单位（c/f）") String unit) {
            try {
                // 调用核心方法获取天气数据
                WeatherResponse response = getWeather(city, unit);
                if (response == null || response.getResults().isEmpty()) {
                    return "未能获取" + city + "的天气数据";
                }

                WeatherResult result = response.getResults().get(0);
                String tempUnit = unit.equals("c") ? "℃" : "℉";

                // 构建返回结果
                return String.format("%s的天气是%s，温度是%s%s，更新时间: %s",
                        result.getLocation().getName(),
                        result.getNow().getText(),
                        result.getNow().getTemperature(),
                        tempUnit,
                        result.getLastUpdate());

            } catch (IOException e) {
                return "获取天气时发生错误: " + e.getMessage();
            }
        }

        // AI服务接口
        interface Assistant {
            @SystemMessage("你是一个天气助手，能够准确返回用户查询的城市天气")
            String chat(@MemoryId int memoryId, @UserMessage String message);
        }
    }

    public static void main(String[] args) {
        // 初始化聊天记忆存储
        // 使用默认实现替代未定义的PersistentChatMemoryStore
        ChatMemoryProvider chatMemoryProvider = memoryId -> MessageWindowChatMemory.builder()
                .id(memoryId)
                .maxMessages(1000)
                .build();

        // 配置DeepSeek模型
        String apiKey = System.getenv("DEEPSEEK_API_KEY");
        if (apiKey == null || apiKey.isEmpty()) {
            apiKey = "your-deepseek-api-key"; // 替换为真实API密钥
        }

        OpenAiChatModel model = OpenAiChatModel.builder()
                .apiKey(apiKey)
                .modelName("deepseek-chat")
                .baseUrl("https://api.deepseek.com")
                .timeout(Duration.ofSeconds(30))
                .logRequests(true)
                .build();

        // 生成AI代理对象
        MyTools.Assistant assistant = AiServices.builder(MyTools.Assistant.class)
                .chatModel(model)
                .chatMemoryProvider(chatMemoryProvider)
                .tools(new MyTools())
                .build();


        // 测试获取天气（华氏度）
        System.out.println(assistant.chat(2, "邵阳的天气如何？用摄氏度显示,帮我把内容发送到3235252003@qq.com邮箱"));
    }
}